//
//  PayViewController.m
//  beautyLamp
//
//  Created by Tam Kwok To Michael on 2017/9/28.
//  Copyright © 2017年 Tam Kwok To Michael. All rights reserved.
//

#import "PayViewController.h"
#import "BLOrder.h"
#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "BLHeader.h"
#import "PayOrderNet.h"
#import <MBProgressHUD.h>
#import <WXApi.h>

@interface PayViewController ()
@property (weak, nonatomic) IBOutlet UIButton *alipay;
@property (weak, nonatomic) IBOutlet UIButton *wechatPay;
@end

@implementation PayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI {
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self.alipay setSelected:YES];
    self.title = @"立即支付";
}

- (IBAction)alipay:(UIButton *)sender {
    if (sender.isSelected) {
        return;
    }
    sender.selected = YES;
    self.wechatPay.selected = NO;
}

- (IBAction)wechatPay:(UIButton *)sender {
    if (sender.isSelected) {
        return;
    }
    sender.selected = YES;
    self.alipay.selected = NO;
}

- (IBAction)pay:(id)sender {
    if (self.alipay.selected) {
        [self dealAlipayWithInfo];
    }else {
        [self dealWithWeChatPay];
    }
}

// 微信支付
- (void)dealWithWeChatPay {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    [PayOrderNet weChatPay:self.order.orderCode completer:^(id result, NSError *error) {
        if (result) {
            [hud hideAnimated:YES];
            //需要创建这个支付对象
            PayReq *req   = [[PayReq alloc] init];
            // 商家id，在注册的时候给的
            req.partnerId = [result objectForKey:@"partnerid"];
            // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
            req.prepayId = [result objectForKey:@"prepayid"];
            // 根据财付通文档填写的数据和签名
            //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
            req.package = @"Sign=WXPay";
            // 随机编码，为了防止重复的，在后台生成
            req.nonceStr  = [result objectForKey:@"noncestr"];
            // 这个是时间戳，也是在后台生成的，为了验证支付的
            NSString * stamp = [result objectForKey:@"timestamp"];
            req.timeStamp = (UInt32)stamp.longLongValue;
            // 这个签名也是后台做的
            req.sign = [result objectForKey:@"sign"];
            //发送请求到微信，等待微信返回onResp
            
            [WXApi sendReq:req];
            
        }else {
            hud.mode = MBProgressHUDModeText;
            hud.label.text = [error localizedDescription];
            [hud hideAnimated:YES afterDelay:2];
        }
        
    }];
}

// 支付宝支付
- (void)dealAlipayWithInfo {
    NSDictionary *dic = @{@"orderCode":self.order.orderCode};
    [PayOrderNet postPayInfo:dic completer:^(id result, NSError *error) {
        NSString *signedString = result;
        // NOTE: 如果加签成功，则继续执行支付
        if (signedString != nil) {
            //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
            NSString *appScheme = @"alisdkdemo";
            // NOTE: 调用支付结果开始支付
            [[AlipaySDK defaultService] payOrder:signedString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                NSString *resultStatus = resultDic[@"resultStatus"];
                NSInteger status = [resultStatus integerValue];
                if (status == 9000 || status == 4000) {
                    NSMutableArray *controllers = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
                    if ([controllers.lastObject class] == [PayViewController class]) {
                        [controllers removeLastObject];
                        [self.navigationController setViewControllers:controllers];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"payNotification" object:nil];
                    }
                }  else if (status == 6001) {
                    hud.label.text = @"用户中途取消!";
                }  else if (status == 6002) {
                    hud.label.text = @"网络连接出错!";
                }   else {
                    hud.label.text = @"请自行检查支付结果！";
                }
                [hud hideAnimated:YES afterDelay:3];
            }];
        }

    }];
}

@end
